package com.spring.demo.untils.document;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.spring.demo.untils.document.dto.Blood;
import com.spring.demo.untils.document.dto.TemplateContext;
import com.spring.demo.untils.document.handle.conventer.SqlConverter;
import com.spring.demo.untils.document.nio.NioUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author xuweizhi
 * @since 2023/04/26 10:07
 */
public class DocumentUtil1 {


    public static void main(String[] args) throws IOException {
        // List<String> jsonStrList = NioUtil.readLine("/Users/xuweizhi/Documents/root/spring-cloud/spring-demo/src/main/java/com/spring/demo/untils/do11cument/my11.txt", line -> line);
        // String collect = jsonStrList.stream().collect(Collectors.joining(""));
        // List<LisLabTestReportThirdDTO> lisLabTestReportThirdDTOS = JSON.parseArray(collect, LisLabTestReportThirdDTO.class);
        // System.out.println(lisLabTestReportThirdDTOS.stream().map(LisLabTestReportThirdDTO::getApplyNo).distinct().collect(Collectors.joining(",")));

        TemplateContext<Blood> templateContext = TemplateContext.<Blood>builder()
                .outPutFileBase("/Users/xuweizhi/Documents/root/spring-cloud/spring-demo/src/main/java/com/spring/demo/untils/document/file/")
                .sourceFilePath("/Users/xuweizhi/Documents/root/spring-cloud/spring-demo/src/main/java/com/spring/demo/untils/document/my1.txt")
                .template("UPDATE dtc_apply_lab_test_record SET execute_dept_id = 40056052,execute_dept_name = '检验科',system_remark = '徐伟智-门诊检验申请单执行地点订正为检验科' where id = %s;\n")
                .selectSql("SELECT o.id,o.start_time,e.plan_time,e.id as plan_id,e.real_start_time,e.real_end_time,t.id as task_id,t.execute_time,t1.blood_bag_no from")
                .size(999)
                .clazz(Blood.class)
                .outPutFileBaseSuffix("检查申请单 %d")
                .build();
        Map<String, String> kk = BloodConfig.kk();
        writeResultFile(templateContext, o ->{
            String s = kk.get(o.getBloodBagNo());
            if(!Objects.equals(s,o.getStartTime())){
                System.out.println("#血袋号:" + o.getBloodBagNo() + ",实际执行时间:" + s + ",执行时间：" + o.getStartTime());
                String d = "update dtc_doctor_order set start_time = '" + s + "',system_remark = \"徐伟智-输血医嘱开始时间订正\" where id = "+o.getId()+";";
                String e ="update dtc_doctor_order_executive_plan set plan_time = '" + s + "',real_start_time='" + s + "',system_remark = '徐伟智-输血医嘱开始时间订正' where id ="+o.getPlanId()+";";
                String task="update dtc_doctor_order_task_record set execute_time = '"+s+"',system_remark = \"徐伟智-输血医嘱开始时间订正\" where id ="+o.getTaskId()+";\n";
                System.out.println(d);
                System.out.println(e);
                System.out.println(task);
            }
            return  "";
        } );




    }

    public static <T> void writeResultFile(TemplateContext<T> templateContext, Function<T, String> function) {
        List<T> dataList = excelTxtConvertJsonList(templateContext.getSourceFilePath(), templateContext.getSelectSql(), templateContext.getClazz());
        List<List<T>> dataPartition = Lists.partition(dataList, templateContext.getSize());
        for (int i = 0; i < dataPartition.size(); i++) {
            List<T> orderList = dataPartition.get(i);
            List<String> templateStr = replaceTemplate(orderList, function);
            writeFile(templateStr, templateContext.getOutPutFileBase() + String.format(templateContext.getOutPutFileBaseSuffix(), i));
        }
    }


    public static void writeFile(List<String> list, String filePath) {
        try {
            File file = new File(filePath);
            if(!file.getParentFile().exists()){
                File parentFile = file.getParentFile();
                parentFile.mkdirs();
            }
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            for (String t : list) {
                fileOutputStream.write(t.getBytes());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public static <T> List<T> excelTxtConvertJsonList(String path, String sql, Class<T> clazz) {
        List<String> jsonStrList = NioUtil.readLine(path, line -> JsonMapping.handle(line, SqlConverter.parseClassMeta(sql)));
        return jsonStrList.stream().map(s -> JSON.parseObject(s, clazz)).toList();
    }

    public static <T> List<String> replaceTemplate(List<T> list, Function<T, String> function) {
        return list.stream().map(function).collect(Collectors.toList());
    }

}
